<template>
  <div>
    <div v-if="showPageWhat === 'index'" class="page">
      <div class="fan-wrapper">
        <fan-container :word-study-times="wordStudyTimes" @fan-click="fanClick" @fan-center-click="startReview"/>
      </div>
      <!-- 操作按钮 -->
      <div class="button-group">
        <!-- 添加新单词按钮 -->
        <el-button
          :disabled="wordStudyTimes[8]==='0'"
          class="add-btn"
          type="primary"
          icon="fa-solid fa-repeat"
          @click="startReview"
        >
          开始复习
        </el-button>
        <!-- 开始复习按钮 -->
        <el-button
          :disabled="wordStudyTimes[7]==='0'"
          class="review-btn"
          type="success"
          icon="fa-solid fa-person-running"
          @click="showPageWhat='review'"
        >
          继续学新
        </el-button>
        <!-- 单词列表按钮 -->
        <el-button class="list-btn" icon="fa-solid fa-dumbbell" @click="$router.push('/vocabularyTestHome')">
          词汇量测试
        </el-button>
      </div>
      <!-- 优化后的词库选择区域 -->
      <div class="wordbook-container">
        <!-- 当前词库显示 -->
        <div class="current-wordbook">
          <span class="label">当前词库：</span>
          <!-- 切换词库按钮 -->
          <el-button
            class="switch-btn"
            type="text"
            size="mini"
            hover-class="switch-btn--hover"
            @click="showVocabularyVisible = true"
          >
            <i class="fa-solid fa-dice mr-1"/>
            切换词库
          </el-button>
        </div>
        <el-tag size="mini" type="danger">{{ courseInfo.nowStudyBookName }}</el-tag>
      </div>
    </div>

    <!-- 学新 -->
    <word-learning
      v-if="showPageWhat === 'review'"
      @change-view="(what)=>{showPageWhat=what}"
      @startToLearn="startToLearn"
    />

    <!--    学习界面-->
    <learn-page
      v-if="showPageWhat === 'learnPage'"
      :bundle-id="bundleId"
      @change-view="(what)=>{showPageWhat=what}"
      @continue-study="showPageWhat='review'"
    />
    <!-- 词库选择弹框 -->
    <vocabulary-choose-dialog
      v-if="showVocabularyVisible"
      :visible.sync="showVocabularyVisible"
      :student-id="courseInfo.stuId"
      :student-now-student-id="courseInfo.nowStudyBookId"
      @select-confirm="handleLexiconSelect"
    />
    <!--  单词检测  -->
    <studied-check
      v-if="showPageWhat === 'studiedCheck'"
      :check-words="checkWords"
      :show-footer="checkWordsInfo.showFooter"
      :show-item-button="checkWordsInfo.showItemButton"
      :title="checkWordsInfo.title"
      @go-bank="showPageWhat='index'"
      @forget-study="startToLearn"
    />
  </div>
</template>

<script>
import FanContainer from '@/views/component/FanContainer.vue'
import WordLearning from '@/views/course/component/courseTeach/wordLearning/WordLearning.vue'
import VocabularyChooseDialog from '@/views/vocabulary/component/VocabularyChooseDialog.vue'
import { duringClassInfo, earlyCompletionOfClasses, fanSearchWordList, reviewWordList } from '@/api/wordSystemCourse'
import LearnPage from '@/views/course/component/courseTeach/wordLearning/LearnPage.vue'
import StudiedCheck from '@/views/course/component/courseTeach/wordLearning/StudiedCheck.vue'

export default {
  name: 'TraditionalTeaching',
  components: { StudiedCheck, LearnPage, VocabularyChooseDialog, WordLearning, FanContainer },
  data() {
    return {
      showPageWhat: 'index',
      showVocabularyVisible: false,
      courseInfo: {},
      wordStudyTimes: [],
      bundleId: '',
      checkWords: [],
      checkWordsInfo: {},
      timer: null
    }
  },
  watch: {
    'showPageWhat'(val) {
      if (val === 'index') {
        this.getBaseInfo()
      }
    }
  },
  created() {
    this.getBaseInfo()
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer)
  },
  methods: {
    async getBaseInfo() {
      this.courseInfo = await duringClassInfo({ cid: this.$route.query.q1 })
      // 设置页面定时器
      this.scheduledTask()
      this.wordStudyTimes = this.courseInfo.wordStudyTimes
      if (this.wordStudyTimes[8] === '0' && this.wordStudyTimes[7] === '0') {
        this.$msgbox.confirm('', '该书本已学完！', {
          confirmButtonText: '切换词库',
          cancelButtonText: '我已知晓',
          type: 'warning',
          center: true,
          showClose: false,
          closeOnClickModal: false
        }).then(() => {
          this.showVocabularyVisible = true
        }).catch(() => {
        })
      }
    },
    // 设置定时任务
    scheduledTask() {
      // 结束时间戳（毫秒）
      let endTime = this.courseInfo.endTimestamp * 1
      // 预留出10秒时间作为缓冲时间
      endTime = endTime - 10 * 1000

      // 五分钟 & 十秒 音频
      const fiveMinutesAudio = new Audio(require('@/assets/five_minutes_tip.mp3'))
      const tenSecondsAudio = new Audio(require('@/assets/ten_seconds_tip.mp3'))

      // 定时器（每秒检查一次）
      if (this.timer) {
        return
      }
      this.timer = setInterval(async() => {
        const now = Date.now()
        const diff = Math.floor((endTime - now) / 1000) // 剩余秒数

        if (diff <= 0) {
          clearInterval(this.timer)
          try {
            await earlyCompletionOfClasses()
          } finally {
            this.$msgbox({
              title: '友情提示',
              message: '课程已经结束了，告知系统你的下一步选择！',
              showCancelButton: true,
              confirmButtonText: '课后反馈',
              cancelButtonText: '继续上课',
              type: 'warning',
              closeOnClickModal: false,
              showClose: false
            }).then(async() => {
              try {
                await earlyCompletionOfClasses()
              } finally {
                this.$router.push({ path: `/afterClass?cid=${this.$route.query.q1}` })
              }
            }).catch(() => {
              this.$notify({ type: 'warning', message: '系统已经封锁了课堂权限，本堂课程您将无法获取新的数据！' })
            })
          }
          return
        }

        // 五分钟提示
        if (diff === 300) {
          fiveMinutesAudio.play().catch(err => console.error('音频播放失败', err))
        }

        // 10秒提示
        if (diff === 10) {
          tenSecondsAudio.play().catch(err => console.error('音频播放失败', err))
        }
      }, 1000)
    },

    // 选中的词汇本
    handleLexiconSelect(user, lexicon) {
      window.location.reload(true)
    },
    startToLearn(bundleId) {
      this.showPageWhat = 'learnPage'
      this.bundleId = bundleId
    },
    // 复习
    async startReview() {
      this.checkWordsInfo = {
        showFooter: true,
        showItemButton: true,
        title: '已学总复习'
      }
      this.checkWords = await reviewWordList({
        libTypeId: this.courseInfo.nowStudyBookId,
        cid: this.courseInfo.cid
      })
      this.showPageWhat = 'studiedCheck'
    },
    async fanClick(fanIndex) {
      this.checkWordsInfo = {
        showFooter: false,
        showItemButton: false,
        title: '未学单词'
      }
      // 默认为生词
      let type = -2
      if (fanIndex >= 7) {
        // 掌握
        type = -1
        this.checkWordsInfo.title = '已掌握单词'
      } else if (fanIndex > 0) {
        type = fanIndex - 1
        if (type === 0) {
          this.checkWordsInfo.title = '学新单词'
        } else {
          this.checkWordsInfo.title = `${type}次复习单词`
        }
        this.checkWordsInfo.showItemButton = true
        this.checkWordsInfo.showFooter = true
      }
      this.checkWords = await fanSearchWordList({
        libTypeId: this.courseInfo.nowStudyBookId,
        fanIndex: type,
        cid: this.courseInfo.cid
      })
      this.showPageWhat = 'studiedCheck'
    }
  }
}
</script>

<style scoped>
.page {
  height: 100vh; /* 占满视口高度 */
  width: 100vw; /* 占满视口宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.fan-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-group {
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  gap: 16px; /* 按钮之间的间距 */
}

.button-group .el-button {
  margin-left: 0;
}

/* 词库容器：横向布局，对齐方式优化 */
.wordbook-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px; /* 文本与按钮间距 */
  padding: 8px 16px;
  border-radius: 8px;
  background-color: #f8fafc; /* 浅灰背景，区分区域 */
  margin-top: 30px; /* 与上方按钮组拉开距离 */
}

/* 当前词库文本样式 */
.current-wordbook {
  display: flex;
}

/* 标签样式：灰色、小号字体 */
.current-wordbook .label {
  font-size: 12px;
  color: #64748b; /* 深灰，不抢焦点 */
  margin-right: 6px;
  padding: 8px 0;
}

/* 按钮图标与文字间距 */
::v-deep .switch-btn .mr-1 {
  margin-right: 4px;
}
</style>
